.PHONY: all build clean install test run help release

BINARY_NAME=kscan
MAIN_FILE=main.go
VERSION=1.0.1
BUILD_TIME=$(shell date -u '+%Y-%m-%d_%H:%M:%S')
GIT_COMMIT=$(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
LDFLAGS=-ldflags "-s -w -X main.Version=$(VERSION) -X main.BuildTime=$(BUILD_TIME) -X main.GitCommit=$(GIT_COMMIT)"

all: build

# 编译项目
build:
	@echo "编译 $(BINARY_NAME)..."
	@go build -o $(BINARY_NAME) $(MAIN_FILE)
	@echo "编译完成!"

# 编译并生成优化的生产版本
build-prod:
	@echo "编译生产版本 v$(VERSION)..."
	@go build $(LDFLAGS) -o $(BINARY_NAME) $(MAIN_FILE)
	@echo "生产版本编译完成!"

# 清理编译文件
clean:
	@echo "清理编译文件..."
	@rm -f $(BINARY_NAME)
	@rm -f *.json
	@rm -f *.log
	@echo "清理完成!"

# 安装到 GOPATH/bin
install:
	@echo "安装 $(BINARY_NAME) 到 GOPATH/bin..."
	@go install
	@echo "安装完成!"

# 下载依赖
deps:
	@echo "下载依赖..."
	@go mod download
	@go mod tidy
	@echo "依赖下载完成!"

# 运行测试
test:
	@echo "运行测试..."
	@go test -v ./...

# 格式化代码
fmt:
	@echo "格式化代码..."
	@go fmt ./...
	@echo "格式化完成!"

# 代码检查
vet:
	@echo "运行代码检查..."
	@go vet ./...
	@echo "检查完成!"

# 运行示例
run:
	@./$(BINARY_NAME) --help

# 构建多平台发布版本
release:
	@echo "构建发布版本 v$(VERSION)..."
	@mkdir -p dist
	@echo "构建 Linux amd64..."
	@GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o dist/$(BINARY_NAME)-linux-amd64 $(MAIN_FILE)
	@echo "构建 Linux arm64..."
	@GOOS=linux GOARCH=arm64 go build $(LDFLAGS) -o dist/$(BINARY_NAME)-linux-arm64 $(MAIN_FILE)
	@echo "构建 macOS amd64..."
	@GOOS=darwin GOARCH=amd64 go build $(LDFLAGS) -o dist/$(BINARY_NAME)-darwin-amd64 $(MAIN_FILE)
	@echo "构建 macOS arm64..."
	@GOOS=darwin GOARCH=arm64 go build $(LDFLAGS) -o dist/$(BINARY_NAME)-darwin-arm64 $(MAIN_FILE)
	@echo "构建 Windows amd64..."
	@GOOS=windows GOARCH=amd64 go build $(LDFLAGS) -o dist/$(BINARY_NAME)-windows-amd64.exe $(MAIN_FILE)
	@echo "压缩发布文件..."
	@cd dist && for file in $(BINARY_NAME)-*; do tar -czf $$file.tar.gz $$file && rm $$file; done
	@echo "发布版本构建完成! 文件位于 dist/ 目录"

# 显示帮助
help:
	@echo "可用的 make 命令:"
	@echo "  make build      - 编译项目"
	@echo "  make build-prod - 编译优化的生产版本"
	@echo "  make release    - 构建多平台发布版本"
	@echo "  make clean      - 清理编译文件"
	@echo "  make install    - 安装到 GOPATH/bin"
	@echo "  make deps       - 下载依赖"
	@echo "  make test       - 运行测试"
	@echo "  make fmt        - 格式化代码"
	@echo "  make vet        - 代码检查"
	@echo "  make run        - 运行示例"
	@echo "  make help       - 显示此帮助信息"